﻿using Common.MQ;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Text;

namespace Common.Kafka
{
    /// <summary>
    /// kafka构建
    /// </summary>
    public class KafkaBuilder : IMessageQueueBuilder
    {
        internal IMQProducer Producer;
        internal List<MQConsumerBase> Consumers = new List<MQConsumerBase>();
        internal KafkaSetting Setting;
        private readonly IServiceCollection services;
        /// <summary>
        /// kafka构建
        /// </summary>
        /// <param name="setting"></param>
        /// <param name="services"></param>
        public KafkaBuilder(KafkaSetting setting, IServiceCollection services)
        {
            this.Setting = setting;
            this.services = services;
        }
        IMessageQueueBuilder IMessageQueueBuilder.AddConsumer(IDestination queue, params IMessageHandler[] handlers)
        {
            var kcc = queue as KafkaConsumerConfig;
            Consumers.Add(new KafkaConsumer(kcc, handlers));
            return this;
        }

        IMessageQueueBuilder IMessageQueueBuilder.AddProducer(IDestination queue)
        {
            return AddProducer();
        }
        /// <inheritdoc/>
        public KafkaBuilder AddConsumer(KafkaConsumerConfig kcc, params IMessageHandler[] handlers)
        {
            Consumers.Add(new KafkaConsumer(kcc, handlers));
            return this;
        }
        /// <inheritdoc/>
        public KafkaBuilder AddProducer()
        {
            if (Producer == null)
            {
                Producer = new KafkaProducer(Setting);
            }
            return this;
        }
        /// <inheritdoc/>
        public IMessageQueueProvider Build()
        {
            IMessageQueueProvider provider = new KafkaProvider(this);
            services?.AddSingleton(provider);
            return provider;
        }
    }
}
